package com.lanhao.aot.carrierintegration.gls;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.beust.jcommander.internal.Maps;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;

public class GlsUtil {
	private static final Logger LOG = LoggerFactory.getLogger(GlsUtil.class);

	public static final String URL = "https://shipit-wbm-fr01.gls-group.eu:8443/backend/rs/shipments";
	public static final String LOGIN_NAME = "25040137ST";
	public static final String PASSWORD = "Gd0tNTYCvhztsXVtB6Sf";
	public static final String CONTACT_ID = "250aaaXt9D";
	public static final String CUSTOMER_ID = "2500051969";
	public static final String LABEL_FORMAT = "PDF";

//	"Accept", "application/glsVersion1+json, application/json"
//	"Content-Type", "application/glsVersion1+json"
//  Authorization 
//  https://shipit.gls-group.eu/webservices/3_4_19/doxygen/WS-REST-API/rest_web_service_requests_samples.html
	public static void main(String[] args) {
		String Authorization = "Basic " + Base64.encode(LOGIN_NAME + ":" + PASSWORD);
		Map<String, String> headers = Maps.newHashMap();
		headers.put("Accept", "application/glsVersion1+json, application/json");
		headers.put("Content-Type", "application/glsVersion1+json");
		headers.put("Authorization", Authorization);
		JSONObject shipmentRequest = new JSONObject();
		JSONObject shipment = new JSONObject();

		shipment.put("Product", "PARCEL");

		JSONObject consignee = new JSONObject();
		consignee.put("ConsigneeID", "AnHeLogistics");
		
		// 这里的Adress是发件人的信息
		JSONObject address = new JSONObject();
		address.put("Name1", "KunKun");
		address.put("Name2", "");
		address.put("Name3", "");
		address.put("CountryCode", "FR");
		address.put("ZIPCode", "78250");
		address.put("City", "Hardricourt");
		address.put("Street", "666 bd Carnot");
		address.put("StreetNumber", "");
		address.put("eMail", "");
		address.put("ContactPerson", "");
		address.put("MobilePhoneNumber", "0782776186");
		address.put("FixedLinePhonenumber", "");

		consignee.put("Address", address);
		shipment.put("Consignee", consignee);

		JSONObject shipper = new JSONObject();
		shipper.put("ContactID", CONTACT_ID);
		shipment.put("Shipper", shipper);

		JSONArray shipmentUnitArray = new JSONArray();
		JSONObject shipmentUnit = new JSONObject();
		shipmentUnit.put("Weight", 0.25);

		shipmentUnitArray.add(shipmentUnit);
		shipment.put("ShipmentUnit", shipmentUnitArray);
		
		JSONArray serviceArray = new JSONArray();
		JSONObject service = new JSONObject();
		JSONObject shopReturn = new JSONObject();
		
		shopReturn.put("ServiceName", "service_shopreturn");
		shopReturn.put("NumberOfLabels", 10);
		
		service.put("ShopReturn", shopReturn);
		serviceArray.add(service);
		
		shipment.put("Service", serviceArray);
		
		shipmentRequest.put("Shipment", shipment);

		JSONObject printingOptions = new JSONObject();
		JSONObject returnLabels = new JSONObject();
		returnLabels.put("TemplateSet", "NONE");
		returnLabels.put("LabelFormat", LABEL_FORMAT);
		printingOptions.put("ReturnLabels", returnLabels);
		shipmentRequest.put("PrintingOptions", printingOptions);
		String request = shipmentRequest.toJSONString();
		LOG.info("开始请求法国GLS，url={}, header={}, request={}", URL, headers, request);
		HttpResponse execute = HttpRequest.post(URL).addHeaders(headers).body(request).execute();
		int status = execute.getStatus();
		LOG.info("请求法国GLS得到的返回码status={}", status);
		if (status != HttpStatus.HTTP_OK) {
			Map<String, List<String>> respHeader = execute.headers();
			// {args=[["Shipment.Shipper.ContactID","250aaaXt9D11","Shipper does not exist or is not available for the user."]], serverExecutionTime=[2], null=[HTTP/1.1 400 Bad Request], Connection=[keep-alive], error=[INVALID_FIELD_VALUE], message=[Invalid field Shipment.Shipper.ContactID. Value 250aaaXt9D11 is not a valid value. Shipper does not exist or is not available for the user.], Content-Length=[0], Date=[Thu, 11 Jan 2024 08:05:32 GMT]}
			List<String> messageList = respHeader.get("message");
			String errorMessage = "请求接口失败，错误码：" + status;
			if (CollectionUtils.isNotEmpty(messageList)) {
				errorMessage = messageList.get(0);
			}
			LOG.info("获取GLS标签失败，code={}， message={}", status, errorMessage);
			return;
		}
		String respBody = execute.body();
//		LOG.info("请求法国GLS得到的返回值respBody={}", respBody);
		try {
			FileUtils.writeStringToFile(new File("D:/GLS_Resp.txt"), respBody, "UTF-8");
		} catch (IOException e) {
			e.printStackTrace();
		}
		JSONObject respObject = JSON.parseObject(respBody);
		JSONObject createdShipmentObject = respObject.getJSONObject("CreatedShipment");
		JSONArray parcelDataArray = createdShipmentObject.getJSONArray("ParcelData");
		JSONObject parcelDataObject = parcelDataArray.getJSONObject(0);
		String parcelNumber = parcelDataObject.getString("ParcelNumber");

		JSONArray printDataArray = createdShipmentObject.getJSONArray("PrintData");
		JSONObject printDataObject = printDataArray.getJSONObject(0);
		String labelData = printDataObject.getString("Data");
//		String labelFormat = printDataObject.getString("LabelFormat");
		Base64.decodeToFile(labelData, new File("D:/" + parcelNumber + "." + LABEL_FORMAT));
		LOG.info("获取标签成功，单号为parcelNumber={}", parcelNumber);
	}

}
